package com.ftg.learn.mybatis.chapter2.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;
import java.util.Objects;

/**
 * 通用类，完成session的获取
 * @author kangjx
 * @date 2022/10/11
 */
public class SessionBase {

    private static SqlSession session = null;

    /**
     * 获得session操作
     * @return SqlSession
     */
    public static SqlSession getSession(){
        if(Objects.isNull(session)){
            String resource = "com/ftg/learn/mybatis/chapter2/config/configuration.xml";

            try {
                Reader inputStream = Resources.getResourceAsReader(resource);
                SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder();
                SqlSessionFactory ssf = ssfb.build(inputStream);
                session = ssf.openSession(true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return session;
    }

}
